//
//  xsAuthorityCollectionView.m
//  digital_robot_demo
//
//  Created by xskj on 2024/8/30.
// 官方

#import "xsAuthorityCollectionView.h"
  
@interface xsAuthorityCollectionView()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,assign)NSInteger aspectRatioInt;

@property (nonatomic,strong) UIView *tableEmptyView;
@property (nonatomic,weak) UIImageView * tableEmptyImage;
@property (nonatomic,weak) UILabel * tableEmptyLabel;
@property (nonatomic,weak) UIButton *covertableEmptyViewButton;

@property (nonatomic,assign)NSInteger page;
@property (nonatomic,assign)NSInteger categoryId;

@property (nonatomic,assign)CGSize cellSize9_16;

@end

@implementation xsAuthorityCollectionView

- (NSMutableArray *)dataArray{
    if(!_dataArray){
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
//aspectRatio    图片比例 1竖屏 2横屏
- (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout withAspectRatio:(NSInteger)aspectRatio{
    
    self = [super initWithFrame:frame collectionViewLayout:layout];
    if(self){
        self.delegate = self;
        self.dataSource = self;
        [self getSize9_16];
        self.page = 1;
        self.aspectRatioInt = aspectRatio;
        self.backgroundColor = UIColor.clearColor;//COLOR_VCViewBgcolor;
        
        //        //注册cell
        [self registerClass:[xsAuthorityCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([xsAuthorityCollectionViewCell class])];
        [self registerClass:[xsAuthorityCollectionViewHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([xsAuthorityCollectionViewHeadView class])];
        
        [self addSubview:self.tableEmptyView];
        [self.tableEmptyView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self);
            //            make.size.mas_equalTo(CGSizeMake(90, 90+5+21));
            make.size.mas_equalTo(CGSizeMake(250, 250));
        }];
        
        
        
        
        XSWeakSelf;
        self.mj_header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
            
            weakSelf.page = 1;
            [weakSelf.dataArray removeAllObjects];
            
            [self getMyDataWithAspectRatio:aspectRatio];
            
        }];

//        self.mj_footer= [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
//            ++self.page;
//            [self getNumberPeopleDataWithAspectRatio:aspectRatio withCategoryId:categoryId];
//        }];
//        [self getMyDataWithAspectRatio:aspectRatio];
        
        //[self.mj_header beginRefreshing];
    }
    
    return self;
}

- (void)getSize9_16{
    
    // 获取self.topImgBgView.frame  16:9最佳宽高
        CGFloat loveW9  = 9.0*3.0;
        CGFloat loveH16 = 16.0*3.0;
        BOOL xsIsBrek = NO;
        CGFloat topImgBgViewW = kScreenW-20.0-18.0;//-50.0
        CGFloat count = 1.0;
        while (!xsIsBrek) {
                
            CGFloat tempLoveW9 = loveW9 *count;
            CGFloat tempLoveH16 = loveH16 *count;
            
            if(tempLoveW9<topImgBgViewW){
                count=count+1.0;
            }
            else{
                xsIsBrek = YES;
            }
            NSLog(@"loveW9==%f\n",loveW9);
            NSLog(@"loveH16==%f\n",loveH16);
        }
        count = count-1;
    // 108 192
    self.cellSize9_16 = CGSizeMake(loveW9*count, loveH16*count);
    NSLog(@"cellSize9_16==%@\n",NSStringFromCGSize(self.cellSize9_16));//cellSize9_16=={324, 576}
}

#pragma mark - UICollectionViewDataSource
//一共有多少组
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

//每一组有多少个cell
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    self.tableEmptyView.hidden = self.dataArray.count;
    return self.dataArray.count;
}

//每一个cell的内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    xsAuthorityCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([xsAuthorityCollectionViewCell class]) forIndexPath:indexPath];
    
    if (indexPath.row<self.dataArray.count) {
        cell.model = self.dataArray[indexPath.item];
    }
    cell.backgroundColor = UIColor.clearColor;
    cell.contentView.backgroundColor = UIColor.clearColor;
    cell.layer.cornerRadius = 4.0;
    cell.layer.masksToBounds = YES;
    
    return cell;
}

//和tableView差不多, 可设置头部和尾部
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if([kind isEqualToString:UICollectionElementKindSectionHeader])
    {
        xsAuthorityCollectionViewHeadView *headerView = [self dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:NSStringFromClass([xsAuthorityCollectionViewHeadView class]) forIndexPath:indexPath];
        headerView.backgroundColor = UIColor.clearColor;
        return headerView;
    }
//    else if([kind isEqualToString:UICollectionElementKindSectionFooter])
//    {
//        
//    }
    return nil;
}


//每一个分组的上左下右间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5.0, 5.0, 5.0, 5.0);
}

//头部视图的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
//    return CGSizeMake(self.frame.size.width, 45.0);
    return CGSizeMake(self.frame.size.width, 0.10);
}


//定义每一个cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    //CGFloat margin = 5.0*4.0;
//    CGFloat itemW =  (self.frame.size.width-margin)/3.0;
//    CGFloat itemH = itemW*2.0;
    
    CGFloat itemW =  self.cellSize9_16.width/3.0;//(self.frame.size.width-margin)/3.0;
    CGFloat itemH = self.cellSize9_16.height/3.0;//itemW*(4.0/3.0);
    return CGSizeMake(itemW, itemH);
}

//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
//    return 4;
//}
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
//    return 5;
//}

//cell的点击事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.item<self.dataArray.count){
        xsAuthorityCollectionViewCellModel *model = self.dataArray[indexPath.item];
        
        NSLog(@"model.url==%@\n",model.url);
//        if(!model.isAddType){
            if(self.AuthorityCollectionCellCallBackBlock){
                self.AuthorityCollectionCellCallBackBlock(model,2);
            }
//        }
    }
}

//
////在开始移动是调动此代理方法
//- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {
//    NSLog(@"开始移动");
//    return YES;
//}

////在移动结束的时候调用此代理方法
//- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
//    NSLog(@"结束移动");
//
//}

//aspectRatio    图片比例 1竖屏 2横屏
- (void)getMyDataWithAspectRatio:(NSInteger)aspectRatio
{
//
    
    XSWeakSelf;

    
//    NSString *tempUrl = @"https://mall219.writemall.com/bossapi/backgroundImage/list";
    
    NSString *tempUrl = [NSString stringWithFormat:@"%@%@",API_BASEURL_BossIP,@"backgroundImage/list"];
    
//    {
//      "page": 1,
//      "limit": 10,
//      "categoryId": 0,
//      "aspectRatio": 0
//    }
//    type    图片类型 1官方图片 2用户图片
    NSDictionary *pramerDict = @{@"page":[NSString stringWithFormat:@"%ld",self.page],
                                 @"limit":@"100",
                                 @"categoryId":[NSString stringWithFormat:@"%ld",self.categoryId],
                                 @"aspectRatio":@"1"};
    
    [[ZYFDataManager sharedInstance] POST:tempUrl dict:pramerDict succeed:^(id data) {
        
        NSLog(@"官方背景数据--pramerDict==%@--data==%@\n",pramerDict,data);
        
        NSDictionary *dictData = data;
        if([dictData isKindOfClass:[NSDictionary class]]){
            if([dictData[@"code"] isKindOfClass:[NSNumber class]]||[dictData[@"code"] isKindOfClass:[NSString class]]){
                NSInteger codeInt = [dictData[@"code"] integerValue];
                if(codeInt==200){
                    
                    if([dictData[@"data"][@"data"] isKindOfClass:[NSArray class]]){
                        NSArray *dataArr3  = dictData[@"data"][@"data"];
                        
                        if(dataArr3.count>0){
                            for (int ii=0; ii<dataArr3.count; ii++) {
                                NSDictionary *tempFinalDict = dataArr3[ii];
                                xsAuthorityCollectionViewCellModel *md = [xsAuthorityCollectionViewCellModel yy_modelWithDictionary:tempFinalDict];
                                md.isAddType = NO;
                                //md.url = tempFinalDict[@"url"];
                                if([tempFinalDict[@"id"] isKindOfClass:[NSNumber class]]||
                                   [tempFinalDict[@"id"] isKindOfClass:[NSString class]]){
                                   NSString *tempIdStr = [NSString stringWithFormat:@"%ld",[tempFinalDict[@"id"] integerValue]];
                                    md.Id = [tempIdStr integerValue];
                                }
                                md.aspectRatio = weakSelf.aspectRatioInt;
                                [weakSelf.dataArray addObject:md];
                            }
                            
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [weakSelf stopEndRefresh:weakSelf.dataArray];
                            });
                        }
                        else{
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [weakSelf stopEndRefresh:nil];
                            });
                        }
                    }
                    else{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [weakSelf stopEndRefresh:nil];
                        });
                    }
                    
                }
                else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf stopEndRefresh:nil];
                    });
                }
            }
            else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf stopEndRefresh:nil];
                });
            }
        }
        else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf stopEndRefresh:nil];
            });
        }
        
    } failure:^(NSDictionary *error) {
        NSLog(@"getAudioDataWithAspectRatio--error.description==%@\n",error.description);
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf stopEndRefresh:nil];
        });
    }];
}


- (UIView *)tableEmptyView{
    
    if (!_tableEmptyView) {
        _tableEmptyView = [[UIView alloc] init];
        _tableEmptyView.backgroundColor = UIColor.clearColor;
        
        
        UITapGestureRecognizer *tableEmptyViewRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableEmptyImageGestureEvent:)];
        [_tableEmptyView addGestureRecognizer:tableEmptyViewRecognizer];
        
        UIImageView *tableEmptyImage = [[UIImageView alloc] init];
        tableEmptyImage.image = [UIImage imageNamed:@"CYNotSearchResultData"];
        [_tableEmptyView addSubview:tableEmptyImage];
        tableEmptyImage.backgroundColor = UIColor.clearColor;
        self.tableEmptyImage = tableEmptyImage;
        
        UILabel *tableEmptyLabel = [[UILabel alloc] init];
        tableEmptyLabel.text = @"暂无数据";//kLocalizedString(@"暂无数据");
        tableEmptyLabel.font = [UIFont systemFontOfSize:16];//Font(16);
        tableEmptyLabel.numberOfLines = 0;
        tableEmptyLabel.textAlignment = NSTextAlignmentCenter;
        tableEmptyLabel.textColor = COLOR_HEX(0x999999);
        [_tableEmptyView addSubview:tableEmptyLabel];
        self.tableEmptyLabel = tableEmptyLabel;
        
        tableEmptyImage.userInteractionEnabled = YES;
        tableEmptyLabel.userInteractionEnabled = YES;

        UITapGestureRecognizer *tableEmptyImageRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableEmptyImageGestureEvent:)];
        [tableEmptyImage addGestureRecognizer:tableEmptyImageRecognizer];

        UITapGestureRecognizer *tableEmptyLabelRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableEmptyLabelGestureEvent:)];
        [tableEmptyLabel addGestureRecognizer:tableEmptyLabelRecognizer];
        
        [tableEmptyImage mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_tableEmptyView);
            make.centerY.equalTo(_tableEmptyView.mas_centerY).offset(-10);
            make.size.mas_equalTo(CGSizeMake(80.55, 86.58));
        }];
        [tableEmptyLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_tableEmptyView);
            make.top.equalTo(tableEmptyImage.mas_bottom).offset(5);
        }];
        //
        //        UIButton *covertableEmptyViewButton = [UIButton buttonWithType:UIButtonTypeCustom];
        //        covertableEmptyViewButton.backgroundColor = UIColor.purpleColor;//UIColor.clearColor;
        //        [_tableEmptyView addSubview:covertableEmptyViewButton];
        //        self.covertableEmptyViewButton = covertableEmptyViewButton;
        //        XSWeakSelf;
        //        [covertableEmptyViewButton addTapRunWithBlock:^(UIButton * _Nonnull YSBtn) {
        //            if(weakSelf.tableViewNotContentDataBgViewBeClickEvent){
        //                weakSelf.tableViewNotContentDataBgViewBeClickEvent();
        //            }
        //        }];
        
    }
    return _tableEmptyView;
    
}
- (void)tableEmptyImageGestureEvent:(UITapGestureRecognizer *)sender{
    
    [self tableEmptyLabelGestureEvent:sender];
}
- (void)tableEmptyLabelGestureEvent:(UITapGestureRecognizer *)sender{
    
    NSLog(@"tableEmptyLabelGestureEvent");
    
    if(self.dataArray.count<=0){
        [self.mj_header beginRefreshing];
    }
}


#pragma mark - stopEndRefresh
- (void)stopEndRefresh:(NSArray *) array {
    
    if (self.page  == 1) {
        if (self.mj_footer.isRefreshing) {
            [self.mj_footer endRefreshing];
        }
        [self.mj_header endRefreshing];
        [self.mj_footer resetNoMoreData];
    }else {
        if (array.count > 1) {
            [self.mj_footer endRefreshing];
        }else {
            [self.mj_footer endRefreshingWithNoMoreData];
        }
    }
    
    __weak typeof(self) weakself = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakself reloadData];
    });
}

- (void)xsAuthorityCollectionLoadDataWithId:(NSInteger)IdInt{
    
    [self.dataArray removeAllObjects];
    self.page = 1;
    
    self.categoryId = IdInt;
    [self getMyDataWithAspectRatio:self.aspectRatioInt];
    
}

- (NSArray *)xsCollectionViewDataArray{
    return self.dataArray;
}


@end

